package com.myweb;

import java.io.IOException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns = "/*")
public class MyWebFilter implements Filter {

  private Map<String, Class<?>> actionMap = null;

  /**
   * Default constructor.
   */
  public MyWebFilter() {
    // TODO Auto-generated constructor stub
  }

  /**
   * @see Filter#destroy()
   */
  @Override
  public void destroy() {
    // TODO Auto-generated method stub
  }

  /**
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    WebRequest webRequest = new WebRequest(req);
    WebResponse webResponse = new WebResponse();
    String url = req.getRequestURI().replaceFirst(req.getContextPath() + "/", "");

    Class<?> class1 = (Class<?>) actionMap.get(url);

    if (class1 != null) {
      try {
        WebAction action = (WebAction) class1.newInstance();
        System.out.println("do " + action);
        action.validate(webRequest);

        action.process(webRequest, webResponse);
        req.setAttribute("RESULT", webResponse.getResult());
        String path = action.getRenderer();
        if (path != null) {
          RequestDispatcher dispatcher = request.getRequestDispatcher(path);
          dispatcher.include(req, res);
          res.flushBuffer();
        }
      } catch (InstantiationException | IllegalAccessException | WebException | ServletException | IOException e) {
        req.setAttribute("RESULT", e);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/error.jsp");
        dispatcher.include(req, res);
        res.flushBuffer();
      } catch(Exception e){
        req.setAttribute("RESULT", e);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/error.jsp");
        dispatcher.include(req, res);
        res.flushBuffer();
      }
    } else {
      chain.doFilter(request, response);
    }
  }

  /**
   * @see Filter#init(FilterConfig)
   */
  @SuppressWarnings("unchecked")
  @Override
  public void init(FilterConfig fConfig) throws ServletException {
    ServletContext context = fConfig.getServletContext();
    actionMap = (Map<String, Class<?>>) context.getAttribute("ACTION_MAP");
  }
}
